function showCheck(a) {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.clearRect(0, 0, 1000, 1000);
    ctx.font = "80px 'Microsoft Yahei'";
    ctx.fillText(a, 0, 100);
    ctx.fillStyle = "rgba(255,255,255,.9)";
}

var code;

function createCode() {
    code = "";
    var codeLength = 4;
    var selectChar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
    for (var i = 0; i < codeLength; i++) {
        var charIndex = Math.floor(Math.random() * 60);
        code += selectChar[charIndex];
    }
    if (code.length != codeLength) {
        createCode();
    }
    showCheck(code);
}

function KeyDown() {
    if (event.keyCode === 13)  //回车键的键值为13
        validate();
}

//验证验证码是否一致
function validate() {
    $('#login').text('正在登录...');
    var inputCode = document.getElementById("J_codetext").value.toUpperCase();
    var codeToUp = code.toUpperCase();
    if (inputCode.length <= 0) {
        document.getElementById("J_codetext").setAttribute("placeholder", "输入验证码");
        createCode();
        alert("请输入验证码......");
        $('#login').text('登  录');
        return false;
    } else if (inputCode != codeToUp) {
        document.getElementById("J_codetext").value = "";
        // document.getElementById("J_codetext").setAttribute("placeholder", "验证码错误");
        createCode();
        alert("验证码输入错误，请重新输入......");
        $('#login').text('登  录');
        return false;
    } else {
        createCode();
        let loginName = $("#loginName").val();
        let password = $("#password").val();

        $.ajax({
            type: "POST",
            url: "/checkLogin",
            data: {"loginName": loginName, "password":password},
            success: function (data) {
                if (data.code === "200") {
                    $.cookie('LoginName', data.data.LoginName);
                    $.cookie('RoleIds', data.data.RoleID);
                    $.cookie('RoleName', data.data.RoleName);
                    $.cookie('UserType', data.data.UserType);
                    $.cookie('UserID', data.data.UserID);

                    window.location.href = "/home/index";
                } else {
                    window.location.href = "/login";
                }
            }
        })
    }


}